﻿using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Data;
using LdtJudge.DataEngine.Data.DataParseStorage;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.Collection;
using LdtJudge.DataEngine.Model.DataModel;
using LdtJudge.DataEngine.Model.DataModel.DataParseStorage;
using LdtJudge.DataEngine.Model.DataModel.ElementNode;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataSave;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml;

namespace LdtJudge.DataEngine.Common.DataSave
{
    /// <summary>
    /// 分析结果数据保存
    /// </summary>
    public class DataResultSave
    {

        public static List<RequestDataModel> AnalysisRequests = new List<RequestDataModel>();

        public static List<RequestDataModel> OptRequests = new List<RequestDataModel>();

        /// <summary>
        /// xml结果模板
        /// </summary>
        public XmlDocument xmlTemplate { get; set; }

        /// <summary>
        /// 排序条件
        /// </summary>
        public ReorderModel reorderModel { get; set; }

        /// <summary>
        /// 中层数据层
        /// </summary>
        public DataContext dataContext { get; set; }

        /// <summary>
        /// 数据保存基础路径
        /// </summary>
        private string SaveUrl = ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("ldt.elementcenterfilestore");

        /// <summary>
        /// xml帮助类
        /// </summary>
        private XmlUtilCommon XmlUtilCommon = new XmlUtilCommon();

        public DataResultSave(DataContext context)
        {
            dataContext = context;
        }
       
        /// <summary>
        /// 合库后分析存储方法
        /// </summary>
        /// <param name="shujuneirongmo"></param>
        public void AnalysisDataSaveNew(An_shujuneirong shujuneirongmo)
        {
            //案件实体信息
            XmlDocument Analysismodel = new XmlDocument();
            Analysismodel.LoadXml(XmlUtility.XmlUtility.SerializeToXml<DataSoursModel>(dataContext.DataLayerAns.AnalysisResultsDataModel).Replace("&#xD;",""));
            string analysistr = XmlUtility.XmlUtility.SerializeToXml<DataSoursModel>(dataContext.DataLayerAns.AnalysisResultsDataModel).Replace("&#xD;", "");
            ResultsDataSave(shujuneirongmo.Shujuid, analysistr, "1", 1);

            //案由实体信息
            foreach (var dataModelResult in dataContext.DataLayerAns.ElementAnalsisDataModelResults)
            {
                DataSoursModel causeDataSoursModel = new DataSoursModel();
                causeDataSoursModel.dataModelList = dataModelResult.Value;
                XmlDocument causeDocument = new XmlDocument();
                causeDocument.LoadXml(XmlUtility.XmlUtility.SerializeToXml<DataSoursModel>(causeDataSoursModel));
                ResultsDataSave(shujuneirongmo.Shujuid, causeDocument.OuterXml, "2", 1, dataModelResult.Key);
            }
           
            //案件中心实体数据,由于分析过程结果，案件实体与案件中心实体一样，所以用一个对象；
            ResultsDataSave(shujuneirongmo.Shujuid, Analysismodel.OuterXml, "3",1);
            //案件内容XML数据回填
            XmlDocument caseXMLDocument = new XmlDocument();
            caseXMLDocument = XmlUtilCommon.DataModelByXml(dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList, "");
            ResultsDataSave(shujuneirongmo.Shujuid, caseXMLDocument.OuterXml, "4",1);

            //保存法官确认要素数据
            DataSoursModel judgeConfirmDataSoursModel = dataContext.DataLayerAns.JudgeConfirmDataModel;
            if(judgeConfirmDataSoursModel!=null && judgeConfirmDataSoursModel.dataModelList!=null && judgeConfirmDataSoursModel.dataModelList.Any())
            {
                XmlDocument judgeConfirmDoc = new XmlDocument();
                judgeConfirmDoc.LoadXml(XmlUtility.XmlUtility.SerializeToXml<DataSoursModel>(judgeConfirmDataSoursModel));
                ResultsDataSave(shujuneirongmo.Shujuid, judgeConfirmDoc.OuterXml, "5", 1);
            }                      
        }
        
        /// <summary>
        ///保存优选数据
        /// </summary>
        public void OptimizationSave()
        {
            if (dataContext.DataLayerOpt.SourdatModleList != null)
            {
                XmlDocument sourdataXml = new XmlDocument();
                DataSoursModel soursModel = new DataSoursModel();
                soursModel.dataModelList = dataContext.DataLayerOpt.SourdatModleList;
                string messagesourmodel = XmlUtility.XmlUtility.SerializeToXml<DataSoursModel>(soursModel);
                sourdataXml.LoadXml(messagesourmodel);
                OptimizationDataSave("1", sourdataXml.OuterXml,2);
            }
            if (dataContext.DataLayerOpt.ElementOptimizationResults != null)
            {
                foreach (var dataModelResult in dataContext.DataLayerOpt.ElementOptimizationResults)
                {
                    DataSoursModel causeDataSoursModel = new DataSoursModel();
                    causeDataSoursModel.dataModelList = dataModelResult.Value;
                    XmlDocument causeDocument = new XmlDocument();
                    causeDocument.LoadXml(XmlUtility.XmlUtility.SerializeToXml<DataSoursModel>(causeDataSoursModel));
                    OptimizationDataSave("2", causeDocument.OuterXml, 2, dataModelResult.Key);
                }
            }
            if (dataContext.DataLayerOpt.SourdatModleList!=null)
            {
                //进行数据保存
                XmlDocument sourdataXml = new XmlDocument();
                DataSoursModel soursModel = new DataSoursModel();
                soursModel.dataModelList = dataContext.DataLayerOpt.SourdatModleList;
                string messagesourmodel = XmlUtility.XmlUtility.SerializeToXml<DataSoursModel>(soursModel);
                sourdataXml.LoadXml(messagesourmodel);

                List<AttributeInfo> attributeInfoList = new List<AttributeInfo>();
                int kezuisu = 0;
                int bukezuisu = 0;
                int anyouyoasu = 1;
                int zongsu = 0;
                foreach (var item in soursModel.dataModelList)
                {
                    if (item.AttributesList!=null && item.AttributesList.Count>0)
                    {
                        foreach (var attin in item.AttributesList)
                        {
                            for (int i = 0; i < attin.sourceList.Count; i++)
                            {
                                if (string.IsNullOrEmpty(attin.sourceList[i].Location))
                                {
                                    bukezuisu = bukezuisu + 1;
                                    attin.sourceList[i].zuisu = "不可追溯";
                                    if (!string.IsNullOrEmpty(attin.sourceList[i].OriginalText))
                                    {
                                        attin.sourceList[i].type = "替换正则";
                                    }

                                }
                                else
                                {
                                    kezuisu = kezuisu + 1;
                                    attin.sourceList[i].zuisu = "可追溯";
                                }
                                if (item.XmlPath.IndexOf("案由要素")>-1)
                                {
                                    anyouyoasu = anyouyoasu + 1;
                                    attin.sourceList[i].type = attin.sourceList[i].type+"案由要素";
                                }

                            }

                            zongsu = zongsu + 1;
                            attributeInfoList.Add(attin);
                        }
                    }
                }
                string fm=  JsonConvert.SerializeObject(soursModel.dataModelList);
                var listss = attributeInfoList.Where(a => a.sourceList.FirstOrDefault(b => b.type == "替换正则") != null);
                OptimizationDataSave("3", sourdataXml.OuterXml,2);
            }
            if (dataContext.DataLayerOpt.OptimizationXml != null)
            {
                Stopwatch swtext = new Stopwatch();
                swtext.Start();
                DataSaveOrder dataSaveOrder = new DataSaveOrder();
                //dataSaveOrder.dataContext = dataContext;
                //dataSaveOrder.OrderEvidDataModel(dataContext.DataLayerOpt.SourdatModleList);
                //XmlDocument xml = dataSaveOrder.OrderModel(xmlTemplate, reorderModel, dataContext.DataLayerOpt.SourdatModleList);
                //if (xml!=null && !string.IsNullOrEmpty(xml.OuterXml))
                //{
                //    XmlNodeList nodelist = xml.SelectNodes("/案件信息要素中心");
                //    XmlNode rootNode = nodelist[0];
                //    XmlAttribute xAttributeCaseType = xml.CreateAttribute("案件类型");
                //    xAttributeCaseType.Value = dataContext.DataLayerOpt.CaseType;
                //    rootNode.Attributes.Append(xAttributeCaseType);
                //    XmlAttribute xAttributeCaseId = xml.CreateAttribute("案件Id");
                //    xAttributeCaseId.Value = dataContext.DataLayerOpt.CaseId;
                //    rootNode.Attributes.Append(xAttributeCaseId);
                //    dataContext.DataLayerOpt.OptimizationXml = xml;
                //}
                //else
                //{
                //    XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
                //    dataContext.DataLayerOpt.OptimizationXml= xmlUtilCommon.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList, "");
                //}

                OptimizationDataSave("4", dataContext.DataLayerOpt.OptimizationXml.OuterXml,2);
                swtext.Stop();
            }
        }

        /// <summary>
        /// 保存优选数据
        /// </summary>
        /// <param name="typecode">存储的数据类型</param>
        /// <param name="xmlcontext">需要保存的内容</param>
        private void OptimizationDataSave(string typecode, string xmlcontext,int handleType, string anyouid = "")
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xmlcontext);
            int savetype = 0;
            if (typecode == "4")
            {
                savetype = 1;
            }
            
            DAL_An_anjiancunchu dAL_An_Anjiancunchu = new DAL_An_anjiancunchu();
            An_anjiancunchu existsEntity = dAL_An_Anjiancunchu.Exists(dataContext.DataLayerOpt.CaseId, typecode,anyouid);

            if (existsEntity == null)
            {
                existsEntity = new An_anjiancunchu()
                {
                    Anjiancunchuid = Snowflake.Instance().GetId().ToString(),
                    Anjianid = dataContext.DataLayerOpt.CaseId,
                    Cunchuleixing = typecode,
                    Anyouid=anyouid,
                    Wenjianid = SaveStructData(xmlDocument.OuterXml, savetype,typecode, handleType)
                };
                
                dAL_An_Anjiancunchu.Insert(existsEntity);
                dataContext.InteractiveShow.LogShow("优选数据保存，优选结果：" + existsEntity.Wenjianid + ",优选类型:" + typecode);
            }
            else
            {
                existsEntity.Wenjianid = SaveStructData(xmlDocument.OuterXml, savetype, typecode,handleType);
                dAL_An_Anjiancunchu.Update(existsEntity.Anjiancunchuid, existsEntity.Wenjianid);
                dataContext.InteractiveShow.LogShow("优选数据保存，优选结果：" + existsEntity.Wenjianid + ",优选类型:" + typecode);
            }
        }

        /// <summary>
        /// 存储结果数据，且调用数据存储服务
        /// </summary>
        /// <param name="shujuid">结构数据ID</param>
        /// <param name="jiegouneirong">结构化内容</param>
        /// <param name="cunchuleixing">存储类型ID</param>
        private void ResultsDataSave(string shujuid, string jiegouneirong, string cunchuleixing,int handleType,string anyouid="")
        {
            bool isAdd = true;
            DAL_An_jiegoushujucunchu dAL_An_Jiegoushujucunchu = new DAL_An_jiegoushujucunchu();
            An_jiegoushujucunchu an_Jiegoushujucunchu = new An_jiegoushujucunchu();
            if(cunchuleixing=="5")
            {
                an_Jiegoushujucunchu = dAL_An_Jiegoushujucunchu.GetjiegoushujucunchuByType(shujuid, cunchuleixing);
                if (an_Jiegoushujucunchu != null)
                    isAdd = false;
                else
                    an_Jiegoushujucunchu = new An_jiegoushujucunchu();
            }
            an_Jiegoushujucunchu.Wenjianid = SaveStructData(jiegouneirong, 0, cunchuleixing, handleType);
            if (isAdd==true)
            {
                an_Jiegoushujucunchu.Shujucunchuid = Snowflake.Instance().GetId().ToString();
                an_Jiegoushujucunchu.Shujuid = shujuid;
                an_Jiegoushujucunchu.Cunchuleixing = cunchuleixing;
                if (!string.IsNullOrEmpty(anyouid))
                {
                    an_Jiegoushujucunchu.Anyouid = anyouid;
                }
                dAL_An_Jiegoushujucunchu.Insert(an_Jiegoushujucunchu);
            }
            else
            {
                dAL_An_Jiegoushujucunchu.Update(an_Jiegoushujucunchu);
            }
        }

        /// <summary>
        /// 保存结构化数据
        /// </summary>
        /// <param name="datastr">需要保存的结果数据</param>
        /// <param name="savetype">保存的数据类型0：普通存储数据；1：案件优选结果且需要转换公共库数据</param>
        /// <returns></returns>
        private string SaveStructData(string datastr, int savetype,string cunchuleixing, int handleType)
        {
            string id = "";
            //分析结果数据
            XmlData xmlData = new XmlData();
            xmlData.xmlContent = datastr.Replace("&#x13;", "").Replace("&#x14;", "").Replace("&#x15;", "").Replace("&#xD;", "");
            xmlData.msgID = dataContext.DataCommon.MsgId; 
            xmlData.anjid = dataContext.DataCommon.CaseId;
            xmlData.anjlx = dataContext.DataCommon.CaseType;
            string requestUrl = string.Empty;
            string requestParam = string.Empty;
            switch (savetype)
            {
                case 0:
                    if (dataContext.InteractiveShow?.LogShow!=null)
                    {
                        requestParam = JsonConvert.SerializeObject(xmlData);
                        requestUrl = SaveUrl + "/api/XmlDataManage/SaveXml";
                    }
                    break;
                case 1:
                    //存储该类型，主要是用于通知数据存储将当前要存储结构化数据进行转换为公共库的操作。
                    if (dataContext.InteractiveShow?.LogShow != null)
                    {
                        requestParam = JsonConvert.SerializeObject(xmlData);
                        requestUrl = SaveUrl + "/api/XmlDataManage/SaveXmlWithConvert";
                    }
                    break;
            }
            var postResult = HttpHelp.HttpPostJson(requestUrl, requestParam);
            //var httpClientService = new HttpClientService();
            //string postResult = httpClientService.PostAsync(requestUrl, requestParam).Result;

            dynamic messageModel = JsonConvert.DeserializeObject<dynamic>(postResult);
            if (messageModel.code == "1")
            {
                id = messageModel.body.id;
            }
            RequestDataModel requestData = new RequestDataModel();
            requestData.RequestKey = cunchuleixing;
            requestData.RequestUrl = requestUrl;
            requestData.RequestParam = requestParam;
            requestData.RequestResult = postResult;
            if (handleType == 1)
            {
                AnalysisRequests.Add(requestData);
            }
            else if(handleType==2)
            {
                OptRequests.Add(requestData);
            }
            return id;
        }


        /// <summary>
        /// 获取XML数据
        /// </summary>
        /// <param name="id">XMLid</param>
        /// <returns></returns>
        public XmlDocument ReadDataXML(string id)
        {
            XmlDocument xmlDocument = new XmlDocument();
            dynamic message = HttpHelp.HttpGet(SaveUrl + "/api/XmlDataManage/GetXmlContent/" + id, "");
            string messagex = message;
            xmlDocument.LoadXml(messagex.Replace("&#x13;","").Replace("&#x14;","").Replace("&#x15;","").Replace("&#xD;", ""));
            return xmlDocument;
        }
    }
}
